package cn.sc.summer.exception.wrapper;

import lombok.extern.slf4j.Slf4j;

import javax.servlet.ReadListener;
import javax.servlet.ServletInputStream;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletRequestWrapper;
import java.io.*;
import java.nio.charset.StandardCharsets;

/**
 * 类名：请求体重造，预防xss攻击
 *
 * @author a-xin
 * @date 2024/9/24 09:42
 */
@Slf4j
public abstract class BaseHttpServletRequestWrapper extends HttpServletRequestWrapper {

    /**
     * 新的请求体参数信息
     */
    protected String NEW_BODY;

    /**
     * Constructs a request object wrapping the given request.
     *
     * @param request           the {@link HttpServletRequest} to be wrapped.
     * @throws IllegalArgumentException if the request is null
     */
    public BaseHttpServletRequestWrapper(HttpServletRequest request) {
        super(request);
    }

    /**
     * 重新包装输入流
     *
     * @return 输入流
     */
    @Override
    public ServletInputStream getInputStream() {
        InputStream newInputStream = new ByteArrayInputStream(NEW_BODY.getBytes(StandardCharsets.UTF_8));
        return new ServletInputStream() {

            @Override
            public boolean isFinished() {
                return false;
            }

            @Override
            public boolean isReady() {
                return true;
            }

            @Override
            public void setReadListener(ReadListener readListener) {
                throw new UnsupportedOperationException();
            }

            @Override
            public int read() throws IOException {
                return newInputStream.read();
            }
        };
    }

    @Override
    public BufferedReader getReader() {
        return new BufferedReader(new InputStreamReader(this.getInputStream()));
    }

}
